package org.apache.shardingsphere.spi.database;

import com.google.common.base.Strings;
import org.apache.shardingsphere.core.metadata.datasource.exception.UnrecognizedDatabaseURLException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 *
 * 达梦数据库的数据源元数据,正则分析驱动url,获取连接信息
 *
 * @author springrain
 */
public final class DMDataSourceMetaData  implements DataSourceMetaData {
    private static final int DEFAULT_PORT = 5236;
    private final String hostName;
    private final int port;
    private final String catalog;
    private final String schema;
    private final Pattern pattern = Pattern.compile("jdbc:dm://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+)", Pattern.CASE_INSENSITIVE);

    public DMDataSourceMetaData(final String url) {
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find()) {
            throw new UnrecognizedDatabaseURLException(url, pattern.pattern());
        }
        hostName = matcher.group(1);
        port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2));
        catalog = matcher.group(3);
        schema = null;
    }

    public String getHostName() {
        return this.hostName;
    }

    public int getPort() {
        return this.port;
    }

    public String getCatalog() {
        return this.catalog;
    }

    public String getSchema() {
        return this.schema;
    }

    public Pattern getPattern() {
        return this.pattern;
    }
}

